<template>
  <div id="player"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
import * as aconfig from './aconfig'
// import testMarker from './marker'
// import dataXlsx from './data.json'

const route = useRoute()

let instance = null
let fdapi = null
const cameraPost = ref() // 相机位置
// const cameraAngle = ref() // 相机角度
const setinte = ref(null)
const settime = ref(null)
const isPause = ref(false)
const current = ref(0)

const timer = ref(null) // 定时器
// const currentIndex = ref(0) // 当前设备索引
// const isPopupOpen = ref(false) // 是否开启弹窗
// const startTime = ref() // 开始时间
// const pauseTime = ref() // 暂停时间

// 漫游巡视数据
let roamData = [
  // {
  //   id: '25D4BAC44571859C53F77CAF7BB4B56B',
  //   objectIds: '8a9696d51e8a0a7de47456ec8a01748a94ce452ca4',
  //   point: [538534.464063, 3376863.051875, 34.42949, 3.857834, 36.505806]
  // }
]

// 默认视场角度
const fieldAngle = [
  538560.961768, 3376853.221768, 286.704395, -85.994781, -38.06879, 0
]

// 点击区域标签
const areaTag = [
  {
    name: '220KV区域',
    id: '3AF6E5BE462581549843F5A80D32D289',
    border: ['5DDF6BEE467022F3B24C18950775DFD5'],
    angle: [
      538503.137285, 3376957.482871, 132.686182, -85.995018, 52.674194, 0.000049
    ]
  },
  {
    name: '主控及其低压侧区域',
    id: '8FC466E648F19A57FF30278386E6D2A4',
    border: [
      'EE8B87A14D6EE5759F27EE91D0F9934E',
      '7FEE2B8B413A8EB24450F49F36DD91CE'
    ],
    angle: [
      538538.793281, 3376893.656221, 110.512832, -85.995018, 52.674194, 0.000049
    ]
  },
  {
    name: '500KV区域',
    id: '5BBEBDBB417E3E1ACD793B9A55F23A68',
    border: ['839649E8416899E98752079E085A16B5'],
    angle: [
      538660.676514, 3376814.222425, 173.366094, -85.984863, 142.055435,
      -0.000024
    ]
  }
]

const emit = defineEmits(['click', 'roam-end'])

const props = defineProps({
  type: {
    type: String,
    default: ''
  },
  camera: {
    type: Array,
    default: () => []
  },
  data: {
    type: Object,
    default: () => {}
  }
})

// 重置视场角
function resetAngle(angle) {
  if (!angle) {
    // 当重置视场角时，显示区域边框和标签
    for (const i in areaTag) {
      show([areaTag[i].id, ...areaTag[i].border])
    }
  }

  stopHighlightActor()

  // TODO 重置漫游数据
  clearInterval(setinte.value)
  clearTimeout(settime.value)
  setinte.value = null
  settime.value = null
  isPause.value = true
  emit('roam-modal-close')

  const Angle = angle ?? fieldAngle
  fdapi.camera.set(Angle, 2) // 2秒
}

// 默认视场角【标签ID，模型ID】-高亮设备
function defaultAngle(angle, id) {
  stopHighlightActor()
  angle && fdapi.infoTree.focus(angle)
  id && fdapi.tileLayer.highlightActor('25D4BAC44571859C53F77CAF7BB4B56B', id)
}

/** 通过设备ID来跳转到默认视场角 */
function toDevAngle(id, dis = 3, fly = 2) {
  stopHighlightActor()
  // id &&
  //   fdapi.tileLayer.focusActors(
  //     {
  //       id: '25D4BAC44571859C53F77CAF7BB4B56B',
  //       objectIds: id
  //     },
  //     dis,
  //     fly
  //   )

  id &&
    fdapi.tileLayer.focusActor('25D4BAC44571859C53F77CAF7BB4B56B', id, dis, fly)
  id && fdapi.tileLayer.highlightActor('25D4BAC44571859C53F77CAF7BB4B56B', id)
  // 1 摄像头, 3  设备
}

// 隐藏标签
function hide(id) {
  if (!id) return
  fdapi.infoTree.hide(id)
}

// 显示标签
function show(id) {
  if (!id) return
  fdapi.infoTree.show(id)
}

// 设备高亮
function highlightActor(id) {
  // 单个设备
  if (id.constructor === String) {
    fdapi.tileLayer.highlightActor('25D4BAC44571859C53F77CAF7BB4B56B', id)
  } else if (id.constructor === Array) {
    // 多个设备
    fdapi.tileLayer.highlightActors({
      id: '25D4BAC44571859C53F77CAF7BB4B56B',
      objectIds: id
    })
  }
}

// 取消设备高亮
function stopHighlightActor() {
  // fdapi.tileLayer.stopHighlightActor('25D4BAC44571859C53F77CAF7BB4B56B', id)

  // fdapi.tileLayer.stopHighlightActors({
  //   id: '25D4BAC44571859C53F77CAF7BB4B56B',
  //   objectIds: []
  // })

  fdapi.tileLayer.stopHighlightAllActors() // 停止高亮所有Actor
}

// 漫游巡视
function executeRoam() {
  // 清除边框和区域标签
  for (const i in areaTag) {
    hide([areaTag[i].id, ...areaTag[i].border])
  }

  clearInterval(setinte.value)
  console.log(isPause.value, current.value)

  if (!isPause.value && current.value < roamData.length) {
    resetAngle(roamData[current.value]?.point)
    highlightActor(roamData[current.value]?.objectIds)
    console.log(current.value, roamData[current.value])

    settime.value = setTimeout(() => {
      console.log(`打开弹窗${current.value}`)
      emit('roam2marker2build', roamData[current.value]?.objectIds)
      settime.value = setTimeout(() => {
        emit('roam-modal-close')
        setinte.value = setInterval(executeRoam)
      }, 6000)
      current.value++
      isPause.value = false
    }, 3000)
  } else {
    clearTimeout(settime.value)
    clearInterval(setinte.value)
    settime.value = null
    setinte.value = null
    isPause.value = true
    message.warning('漫游巡视结束')
    console.log('结束遍历')

    emit('roam-end')
  }
}

function pause() {
  clearTimeout(settime.value)
  clearInterval(setinte.value)
  settime.value = null
  setinte.value = null
  isPause.value = true
  emit('roam-modal-close')
  console.log('当前【暂停】索引号：', current.value)
}

function begin() {
  console.clear()
  isPause.value = false
  setinte.value = setInterval(executeRoam)
  console.log('当前【继续】索引号：', current.value)
}

// 数字孪生初始化后
const onReadyFun = async () => {
  console.log('此时可以调API了(onReadyFun)')

  // await getAllStationListFun()
  // count = 0
  fdapi = instance?.getAPI()
  console.log(fdapi, '======getAPI========')

  // 5分钟刷新页面
  // timer.value = setInterval(() => {
  //   refreshPage()
  // }, 5 * 60 * 1000)

  /**
   * 初始化
   * 清空所有自定义物体
   * 清空所有高亮
   * 隐藏风机爆炸
   */
  if (!fdapi) return
  await fdapi.customObject.clear()
  await fdapi.tileLayer.stopHighlightAllActors()
  // await fdapi.tileLayer.hideActor(dicts.fanExplore, dicts.fanBlueObjectId)

  // 漫游效果
  // const ABC = [A, B, C, D]

  // for (const i in ABC) {
  //   setTimeout(() => {
  //     fdapi.camera.set(ABC[i], 2.5)
  //   }, i * 3000)
  // }

  // fdapi.camera.lookAt(A[0], A[1], A[2], 0, A[3], A[4], 0) // 直接定位到视场角
  // fdapi.camera.set(devlist[0].point) // 平缓过渡定位到视场角

  // 循环高亮显示所有巡视点
  // for (const i in devlist) {
  // timer.value = setTimeout(() => {
  //   fdapi.camera.set(devlist[i].point)
  //   fdapi.tileLayer.highlightActor(devlist[i].id, devlist[i].objectIds)
  // }, i * 5000)
  // }

  // TODO 获取巡视点视场角(回显数据)
  if (props.type === 'get') {
    if (props.camera?.length) {
      fdapi.camera.set(props.camera)
    } else {
      console.log('无数据', props.camera)
      fdapi.camera.set(fieldAngle)
    }
  } else {
    // fdapi.camera.set(fieldAngle)
    // fdapi.infoTree.focus('6301')
    // tourAnimation()
    // dataXlsx.slice(0, 0).forEach((item) => {
    //   fdapi.tileLayer.highlightActor(
    //     '25D4BAC44571859C53F77CAF7BB4B56B',
    //     item['设备ID']
    //   )
    // })
    // testMarker(dataXlsx.slice(0, 10))
    // testMarker(dataXlsx)
    // testMarker(['8a8e40f3848a0a7de47456ec8a01748a8c78b32c23'])
    // fdapi.infoTree.hide('1E47269C4BA9EF013643F9A4E7056C2A') // 设备
    // fdapi.infoTree.hide('AFCA2F7E4E9D0F8F19A14093A40880ED') // 监控
    // fdapi.infoTree.show('0F0DA49141BC32E97D8C869804D06831') // 区域

    fdapi.infoTree.get((res) => {
      console.log(res.infotree, '获取图层树信息')
    })

    // TODO 跳转至首页定位到设备上
    if (route.query?.deviceId) {
      // defaultAngle(route.query?.tagId, route.query?.deviceId)
      toDevAngle(route.query?.deviceId)
    } else {
      resetAngle()
    }

    // fdapi.infoTree.focus('4bb0aec1198a0a7de7543f3b5601544bafdb6508fa')
  }

  // 设备变色
  // 设置高亮颜色（全局生效）
  // fdapi.settings.highlightColor('#00ffff')

  // 单个设备变色(高亮)
  // fdapi.tileLayer.highlightActor(
  //   '25D4BAC44571859C53F77CAF7BB4B56B',
  //   '8a8e40f3848a0a7de47456ec8a01748a8c78b32c23'
  // )

  // fdapi.infoTree.focus('6301')
  // await fdapi.infotree.focus(6301) (’);
  // fdapi.infoTree.focus('5FF39A9C4CB25975736F14BB055814A0')
  // fdapi.infoTree.focus('5370F520429E50D091123CB16C63678E')
  // fdapi.infoTree.focus('630029EE488AD582B3430C990F247912')
  // console.log(fdapi.infoTree, '=========infoTree()========')
  // console.log(__g.infoTree)

  // fdapi.infoTree.focus('f4117f91a98a0a7de474c7bd650174f4101935492b')
  // fdapi.tileLayer.highlightActor(
  //   '25D4BAC44571859C53F77CAF7BB4B56B',
  //   '8a8ebe13ca8a0a7de47456ec8a01748a8cf5bf2c46'
  // )

  // fdapi.infoTree.show([
  //   'EE8B87A14D6EE5759F27EE91D0F9934E',
  //   '7FEE2B8B413A8EB24450F49F36DD91CE'
  // ])

  // setTimeout(() => {
  //   // 取消设备高亮
  // fdapi.tileLayer.stopHighlightActor()
  // }, 3000)

  // 默认图层设置
  // let defaultLayerStatus = getStorage('default_layer_status')
  // 宾阳
  // if (useInfo.stationCode === dicts.byPoint && !route.query.layerStatus) {
  //   defaultLayerStatus = '8'
  // }
  // await setLayer(
  //   defaultLayerStatus || (route.query.layerStatus) || '1'
  // )

  // 开启鼠标拾取
  // await fdapi.settings.setMousePickMask(7)
}

// 点击事件交互
const onEventFun = async (event) => {
  // 事件类型 参考交互事件类型枚举对象
  // console.info('监听各类交互事件(onEventFun)', event)
  const eventType = event.eventtype

  // const ID = event.Id || event.ID
  const ObjectID = event.ObjectID || event.Id

  switch (eventType) {
    case 'LeftMouseButtonClick':
      console.info(
        '监听图层【鼠标】点击(LeftMouseButtonClick)事件',
        event,
        ObjectID
      )

      // TODO 点击设备事件
      // if (devlist.some((item) => item.objectIds === ObjectID)) {
      //   // clearTimeout(timer.value)
      //   // 开启弹窗
      //   isPopupOpen.value = true
      //   pauseTime.value = new Date().getTime() // 记录暂停时间
      //   clearInterval(timer.value)
      //   timer.value = null

      //   // const params = devlist.find((item) => item.objectIds === ObjectID)
      //   emit('click', ObjectID)
      // } else {
      //   // TODO 点击标签&设备事件  标签只有Id marker  设备有Id ObjectID TileLayer
      //   emit('marker2build', ObjectID)
      // }

      // 注：高亮设备，只能通过点击设备，通过设备ID高亮设备，标签ID高亮无效
      if (event.Type === 'marker') {
        console.log('点击标签----', ObjectID)
        emit('marker2build', ObjectID)
        // stopHighlightActor()
        // highlightActor(ObjectID)

        // TODO 处理点击区域标签
        // eslint-disable-next-line no-case-declarations
        const isArea = areaTag.find((item) => item.id === ObjectID)
        if (isArea) {
          resetAngle(isArea.angle)
          hide([isArea.id, ...isArea.border])
        }
      }
      if (event.ObjectID && !event.ObjectID.includes('DX_')) {
        console.log('点击设备')
        emit('marker2build', ObjectID)
        // stopHighlightActor()
        // highlightActor(ObjectID)
      }

      if (props.type === 'get') {
        fdapi.camera.get((res) => {
          console.log(res, '==== 获取相机位置 ====')
          cameraPost.value = res.camera
        })
      }
      break
    default:
      break
  }
}

const close = () => {
  console.log('弹窗关闭')
  // const elapsedTime = pauseTime.value - startTime.value // 计算暂停的时间差
  // const remainingTime = 3000 - (elapsedTime % 3000) // 计算剩余时间
  // timer.value = setTimeout(() => {
  //   // 使用 setTimeout 来调整启动时间
  //   tourAnimation()
  // }, remainingTime)
  // isPopupOpen.value = false
}

const onVideoLoadedFun = () => {
  console.log('视频流加载成功(onVideoLoadedFun)')
}

const onConnCloseFun = async (error) => {
  console.log('连接断开(onConnCloseFun)')
  await instance?.destroy()

  if (route.path === '/') {
    // setinitApi();
    console.error('数字孪生关闭', error)
    message.warning(error.reason || '服务已断开连接')
  }

  // 本机断网重连由api内部实现，代码不做处理
  if ([1006, 4005, 1005].indexOf(error.code) === -1) {
    await instance?.destroy()
    // setinitApi()
  }
  // await instance?.destroy()
  // instance?.signallingConnection.websocket.close()
}

// 初始化API实例
async function initTwinPlayer() {
  // 重置初始渲染场景状态
  await instance?.reset()

  /**
   * 云渲染视频流对象
   * 创建和显示三维视频流
   */
  // 初始化API实例并启动渲染后，将显示视频流，DigitalTwinPlayer对象构造参数查看API开发文档
  // eslint-disable-next-line no-undef
  instance = new DigitalTwinPlayer(
    '10.0.204.5:8080',
    aconfig.playerConfig(
      onReadyFun,
      onEventFun,
      onVideoLoadedFun,
      onConnCloseFun
    )
  )
}

function roaming(data) {
  if (timer.value) {
    message.warning('漫游巡视中，请稍后操作')
  }

  roamData = data.map((item) => {
    if (!item.threeDimensionalParam) {
      message.warning('巡视点数据异常')
    }
    return {
      objectIds: item.deviceId.replace(/[a-z]/g, (match) =>
        match.toUpperCase()
      ),
      point: JSON.parse(item.threeDimensionalParam),
      ...item
    }
  })

  console.log(roamData, '====== 漫游数据 ======')

  // 执行漫游
  isPause.value = false
  current.value = 0
  executeRoam()
}

// TODO 获取视场角度
const getAngle = async () => {
  const { camera } = await fdapi.camera.get()
  return new Promise((resolve, reject) => {
    try {
      console.log(camera)
      resolve(camera)
    } catch (error) {
      reject(error)
    }
  })
}

onMounted(() => {
  initTwinPlayer()
})

onBeforeUnmount(async () => {
  await instance?.destroy()
  console.log('关闭云渲染并释放资源')
})

defineExpose({
  cameraPost,
  hide,
  show,
  close,
  pause,
  begin,
  roaming,
  getAngle,
  resetAngle,
  defaultAngle,
  toDevAngle,
  highlightActor,
  stopHighlightActor
})
</script>

<style lang="less" scoped>
#player {
  position: absolute;
  width: 100%;
  height: 100%;
  pointer-events: auto;
}
</style>
